package com.example.yueliang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.yueliang.common.Result;
import com.example.yueliang.pojo.User;
import com.example.yueliang.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody User user){
        log.info("接收请求成功");
        log.info(user.getUsername());

//        2.根据页面提交的用户名查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        queryWrapper.eq(User::getPassword,user.getPassword());
        User u1 = userService.getOne(queryWrapper);

        if (u1 == null){
            return Result.error("登录失败");
        }else {
            //        将员工id存入Session并返回登录成功结果
            request.getSession().setAttribute("user",u1.getUid());
        }

        return Result.success(u1);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        log.info(user.getUsername()+","+user.getBirthday()+","+user.getSex());

        //1.检查是否存在账号
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User u1 = userService.getOne(queryWrapper);

        //2.如果不存在,往user表中添加数据
        if (u1 != null){
            return Result.error("用户已存在");
        }

        userService.save(user);

        return Result.success("注册成功");
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success("退出成功");
    }

}
